package com.wwd.movie.login.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.wwd.movie.common.AjaxResult;
import com.wwd.movie.common.UserContext;
import com.wwd.movie.common.constant.CacheConstants;
import com.wwd.movie.common.constant.Constants;
import com.wwd.movie.common.utils.RedisCache;
import com.wwd.movie.login.domain.dto.LoginDTO;
import com.wwd.movie.login.domain.dto.UpdatePwdDTO;
import com.wwd.movie.login.domain.entity.MovieUser;
import com.wwd.movie.login.domain.vo.GetUserProfileVO;
import com.wwd.movie.login.service.MovieUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping
@RequiredArgsConstructor
public class LoginController {

    private final MovieUserService movieUserService;
    private final RedisCache redisCache;


    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginDTO dto) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = movieUserService.login(dto.getUsername(), dto.getPassword(), dto.getCode(),
                dto.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode() throws IOException {
        AjaxResult ajax = AjaxResult.success();

        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        // 创建 LineCaptcha，宽200，高100，4位字符，0条干扰线
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 0);

        // 获取验证码字符串
        String code = lineCaptcha.getCode();

        // 存入 Redis
        redisCache.set(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 将验证码图片转 Base64
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        lineCaptcha.write(os); // 输出到流
        String base64Img = Base64.getEncoder().encodeToString(os.toByteArray());

        ajax.put("uuid", uuid);
        ajax.put("img", base64Img);
        return ajax;
    }


    @PostMapping("/register")
    public AjaxResult register(@RequestBody LoginDTO dto) {
        return movieUserService.register(dto);
    }


    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        MovieUser user = UserContext.getUser();
        GetUserProfileVO vo = new GetUserProfileVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setNickname(user.getNickname());
        vo.setAvatar(user.getAvatar());
        vo.setStatus(user.getStatus());
        vo.setLastLoginTime(user.getLastLoginTime());
        vo.setCreateTime(user.getCreateTime());
        vo.setUpdateTime(user.getUpdateTime());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", vo);
        return ajax;
    }


    @GetMapping("getUserProfile")
    public AjaxResult getUserProfile() {
        MovieUser user = UserContext.getUser();
        GetUserProfileVO vo = new GetUserProfileVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setNickname(user.getNickname());
        vo.setAvatar(user.getAvatar());
        vo.setStatus(user.getStatus());
        vo.setLastLoginTime(user.getLastLoginTime());
        vo.setCreateTime(user.getCreateTime());
        vo.setUpdateTime(user.getUpdateTime());
        return AjaxResult.success(vo);
    }

    @PutMapping("updateUserProfile")
    public AjaxResult updateUserProfile(@RequestBody GetUserProfileVO vo) {
        return movieUserService.updateUserProfile(vo);
    }

    @PutMapping("updatePwd")
    public AjaxResult updatePwd(@RequestBody UpdatePwdDTO dto) {
        return movieUserService.updatePwd(dto);
    }

    @PostMapping("uploadAvatar")
    public AjaxResult uploadAvatar(@RequestParam("avatarfile") MultipartFile file){
        return movieUserService.uploadAvatar(file);
    }


}
